﻿using LdtCommonLibraryHttp;
using Microsoft.Extensions.Hosting;
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace AuthorityCenter
{
    /// <summary>
    /// 授权后台服务
    /// </summary>
    public class AuthorQTService : BackgroundService
    {
        public static bool IsV1 = false;
        private static readonly Process myProcess = new Process();
        private readonly IHttpHelper httpHelper;
        public AuthorQTService(IHttpHelper httpHelper)
        {
            this.httpHelper = httpHelper;
        }
        /// <summary>
        /// 服务启动执行函数
        /// </summary>
        /// <param name="stoppingToken">停止标记</param>
        /// <returns></returns>
        protected override Task ExecuteAsync(CancellationToken stoppingToken)
        {
            Task.Run(async () =>
            {
                Thread.Sleep(1000);
                if (!IsLinux())
                {
                    RunProcess("AuthorityCenterWeb.exe", "");
                }
                else
                {
                    RunProcess("/bin/sh", "AuthorityCenterWeb.sh");
                }
                Thread.Sleep(3000);
                try
                {
                    var r = await httpHelper.GetAsync($"http://localhost:60006/authority/v1/gethcode?time={DateTime.Now.Ticks}");
                    if (r.StatusCode == System.Net.HttpStatusCode.OK)
                    {
                        var result = MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(await r.Content.ReadAsStringAsync())).Aggregate("", (current, b) => current + b.ToString("x2"));
                        if (File.Exists("hcode"))
                        {
                            var s = File.ReadAllText("hcode");
                            if (s != result)
                            {
                                myProcess.Kill();
                                Console.WriteLine("硬件码校验不一致");
                            }
                        }
                        else
                        {
                            File.WriteAllText("hcode", result);
                        }
                    }
                    else
                    {
                        myProcess.Kill();
                        Console.WriteLine(r.StatusCode);
                    }
                }
                catch (Exception ex)
                {
                    myProcess.Kill();
                    Console.WriteLine(ex);
                }
            });
            return Task.CompletedTask;
        }
        /// <summary>
        /// 运行外部程序
        /// </summary>
        /// <param name="fileName">程序文件</param>
        /// <param name="appParam">程序参数</param>
        /// <returns></returns>
        private static int RunProcess(string fileName, string appParam)
        {
            int returnValue = -1;
            try
            {
                DirectoryInfo dir = new DirectoryInfo(AppContext.BaseDirectory);
                string servicePath = "";
                if (IsLinux())
                {
                    Console.WriteLine($"系统架构：{RuntimeInformation.OSArchitecture}");
                    if (RuntimeInformation.OSArchitecture == Architecture.X64 || RuntimeInformation.OSArchitecture == Architecture.X86)
                    {
                        servicePath = Path.Combine(dir.FullName, "authorcenter_linux");
                    }
                    else
                    {
                        servicePath = Path.Combine(dir.FullName, "authorcenter_linux_arm");
                    }
                }
                else
                {
                    servicePath = Path.Combine(dir.FullName, "authorcenter_window");
                }
                var str = File.ReadAllLines(Path.Combine(servicePath, "etc", "AuthorityCenterWeb.ini")).LastOrDefault(p => p.StartsWith("v1"));
                if (!string.IsNullOrEmpty(str))
                {
                    IsV1 = Convert.ToBoolean(str.Split('=')[1].Trim());
                }
                ProcessStartInfo myProcessStartInfo = new ProcessStartInfo(Path.Combine(servicePath, fileName), appParam)
                {
                    WorkingDirectory = servicePath,
                    WindowStyle = ProcessWindowStyle.Normal
                };
                myProcess.StartInfo = myProcessStartInfo;
                myProcess.Start();
            }
            catch (Exception ex)
            {
                Console.Write("出现错误" + ex.Message);
            }
            return returnValue;
        }
        /// <summary>
        /// 是否linux系统
        /// </summary>
        /// <returns>true/false</returns>
        public static bool IsLinux()
        {
            return RuntimeInformation.IsOSPlatform(OSPlatform.Linux);
        }


    }
}
